import originalAxios from 'axios'
import CodeMsg from './code-msg'
import callApp from '@/assets/js/jsbridge'

const ISSUCCESS = 1
const UPLOADSUCCESS = 'SUCCESS'
// 601登出
// 1001 帐号被锁定，请联系管理员
// 1002 用户名不存在或未生效，请重新输入
// 1008 帐号未生效
const NOTLOGIN = [601, 1001, 1008]
const creator = (headers = true) => {
  // 设置不缓存请求
  const axiosObj = headers ? originalAxios.create({
    headers: {
      'If-Modified-Since': 0
    }
  }) : originalAxios.create()

  // 动态添加token
  axiosObj.interceptors.request.use(async (config) => {
    // api url地址中包含动态变量/xx/{id}/xx，请求参数params、data中存在id，替换api url中id，并删除请求参数中的id
    let arr = config.url.match(/[\{][^\}]+[\}]/g)
    let data = config.params || config.data
    if (arr && data) {
      arr.forEach((items, index) => {
        let item = items.slice(1, -1)
        config.url = config.url.replace(new RegExp(`\[{\]${item}\[}\]`), data[item])
        config.params && delete config.params[item]
        config.data && delete config.data[item]
      })
      if (config.params && Object.keys(config.params).length <= 0) {
        config.params = null
      }
      if (config.data && Object.keys(config.data).length <= 0) {
        config.data = null
      }
    }
    headers && (config.headers['Access-Token'] = await callApp.getToken())
    return config
  })

  // 要求接口必须有code, code为0时为成功，code为非0时失败
  axiosObj.interceptors.response.use(function (response) {
    // 请求响应状态码为200的情况
    try {
      response = response.data

      // 数据结构正确，但State不是1(即数据异常)
      if (typeof response.State === 'number' || response.state === UPLOADSUCCESS) {
        if (response.State === ISSUCCESS || response.state === UPLOADSUCCESS) {
          return response
        }
        if (NOTLOGIN.indexOf(response.State) > -1) {
          callApp.toLogin(true)
        }
        return Promise.resolve({
          State: response.State,
          Message: CodeMsg.resolveDataError(response.State, response.Message),
          response
        })
      }
      throw new Error('State不是数字')
    } catch (error) {
      // 数据不是预先规定的数据格式
      return Promise.resolve({
        State: '$API-DATA-ERROR',
        Message: '接口数据非预期[$API-DATA-ERROR]',
        error
      })
    }
  }, function (error) {
    // 请求返回状态码非200，或发出的请求服务端认为是错误的
    let reason = {}

    // 响应失败
    if (error.response) {
      reason = {
        State: '$RESPONCE-ERROR',
        Message: CodeMsg.resolveResponseError(error.response),
        error
      }
      // 发送的请求有问题
    } else if (error.request) {
      reason = {
        State: '$REQUEST-ERROR',
        Message: `${CodeMsg.resolveRequestError()}[$REQUEST-ERROR]`,
        error
      }
    } else {
      reason = {
        State: '$HTTP-ERROR',
        Message: '接口错误[$HTTP-ERROR]',
        error
      }
    }
    return Promise.resolve(reason)
  })
  axiosObj.CancelToken = originalAxios.CancelToken
  axiosObj.isCancel = originalAxios.isCancel
  return axiosObj
}

export const axios = creator()

export const nonHeaderAxios = creator(false)
